const cp = require('child_process');
const { resolve } = require('path');
const { nanoid } = require('nanoid');
const Qiniu = require('qiniu');
const qiniuKeys = require('../config/config').qiniu.keys;

module.exports = {
  //子进程控制
  startProcess (options) {

    //参数列表
    //options file message exit error
    const script = resolve(__dirname, '../controllers/crawlers/' + options.file),
          //通过路径引入脚本 传入三个处理函数
          child = cp.fork(script, []);

    let invoked = false;

    child.on('message', (data) => {
      options.message(data);
    });

    child.on('exit', (code) => {
      if(invoked){
        return ;
      }

      invoked = true;
      options.exit(code);
    });

    child.on('error', (err) => {
      if(invoked){
        return ;
      }
      invoked = true;
      options.error(err);
    });
  },
  
  qiniuUpload (options) {
    const mac = new Qiniu.auth.digest.Mac(qiniuKeys.ak, qiniuKeys.sk),
          conf = new Qiniu.conf.Config(),
          client = new Qiniu.rs.BucketManager(mac, conf),
          key = nanoid() + options.ext; //文件名+ 后缀
    return new Promise((resolve, reject) => {
      client.fetch(options.url, options.bucket, key, (error, ret, info) => {
        if(error){
          reject(error);
        }else {
          // console.log(info.statusCode)
          if(info.statusCode === 200){
            resolve( {key} );
          }else {
            reject(info);
          }
        }
      })
    })
  }
}